# coding=utf-8
'''
author:董新强
createdate:
description:
'''
import time
from contextlib import contextmanager

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from setting import MYSQL_DB_CONN_STR

DbEngine = create_engine(MYSQL_DB_CONN_STR, echo=False, pool_size=50, pool_recycle=3600)


class DbSession:

    @classmethod
    @contextmanager
    def create(cls):

        exception, st = None, time.time()
        cl_session = scoped_session(sessionmaker(DbEngine))

        session = cl_session()
        try:
            yield session
            session.commit()
        except Exception as e:
            exception = e

            try:
                session.rollback()
            except Exception as e:
                print(e)
        finally:
            if cl_session is not None:
                cl_session.remove()

        # ----------重新抛出异常----------
        if exception:
            raise exception
